//
//  NetWorkingPhotoLibraryImageLoader.m
//  YuanXinNetWorking
//
//  Created by 晏德智 on 2016/12/13.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "NetWorkingImageLoader.h"
#if __has_include(<React/RCTBridgeModule.h>)
#import <React/RCTUtils.h>
#else
#import <React/RCTUtils.h>
#endif
#import <React/RCTImageUtils.h>

#import "NetworkingManager.h"
#import "SystemFileManager.h"
#import "YuanXinImageCache.h"

#define  defaultDownUrl @"FileDownService/down/file"

/**
 * 只要不是重定义为其它类型，可以重定义。
 * 重定义 RCTImageLoaderPartialLoadBlock
 * rn 在 0.38.1 上定义了该类型，RCTImageURLLoader 协议方法也相应变了，
 * 所以在低于此版本的 rn 上找不到这个类型，这里重定义一下保证可以找到
 * 。。不得已出此下策，若以后 rn 有新版本改变该类型则需要和 rn 版本同步再兼容
 */
typedef void (^RCTImageLoaderPartialLoadBlock)(UIImage *image);

@implementation NetWorkingImageLoader

RCT_EXPORT_MODULE()

@synthesize bridge = _bridge;

- (BOOL)canLoadImageURL:(NSURL *)requestURL
{
    BOOL canLoad = [requestURL.scheme caseInsensitiveCompare:@"YuanXin-File"] == NSOrderedSame;
    if ([NetworkingManager shareInstance].canLoadWebImageURL) {
        BOOL maybeImageURL = [self maybeImage:requestURL];
        canLoad = [requestURL.scheme caseInsensitiveCompare:@"YuanXin-File"] == NSOrderedSame
                  || ([requestURL.scheme caseInsensitiveCompare:@"http"] == NSOrderedSame && ![requestURL.absoluteString hasPrefix:@"http://localhost:"] && maybeImageURL)
                  || ([requestURL.scheme caseInsensitiveCompare:@"https"] == NSOrderedSame && maybeImageURL);
    }
    return canLoad;
}

- (NSSet<NSString *> *)supportedExt {
    static NSSet<NSString *> *ext = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // image extension
        ext = [[NSSet alloc] initWithObjects:@"jpe", @"jpeg", @"jpg", @"png", @"x-png", nil];
    });
    
    return ext;
}

- (BOOL)maybeImage:(NSURL *)imageURL {
    NSSet<NSString *> *ext = [self supportedExt];
    
    BOOL maybeImageURL = NO;
    //NSString *extension = [requestURL pathExtension];
    NSString *fileName = [imageURL.absoluteString componentsSeparatedByString:@"/"].lastObject;
    NSString *extension = [fileName pathExtension];
    NSEnumerator *enumerator = [ext objectEnumerator];
    NSString *value;
    while (value = [enumerator nextObject]) {
        maybeImageURL = [extension isEqualToString:value];
        if (maybeImageURL) {
            return maybeImageURL;
        }
        maybeImageURL = [extension hasPrefix:value];
        if (maybeImageURL) {
            return maybeImageURL;
        }
    }
    
    maybeImageURL = [imageURL.absoluteString containsString:@"GetImage?userCode="]; // 兼容移动办公的特殊需求。。
    
    return maybeImageURL;
}

- (RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
                                              size:(CGSize)size
                                             scale:(CGFloat)scale
                                        resizeMode:(RCTResizeMode)resizeMode
                                   progressHandler:(RCTImageLoaderProgressBlock)progressHandler
                                 completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
{
    return [self loadImageForURL:imageURL size:size scale:scale resizeMode:resizeMode progressHandler:progressHandler partialLoadHandler:nil completionHandler:completionHandler];
}

- (RCTImageLoaderCancellationBlock)loadImageForURL:(NSURL *)imageURL
                                              size:(CGSize)size
                                             scale:(CGFloat)scale
                                        resizeMode:(RCTResizeMode)resizeMode
                                   progressHandler:(RCTImageLoaderProgressBlock)progressHandler
                                partialLoadHandler:(RCTImageLoaderPartialLoadBlock)partialLoadHandler
                                 completionHandler:(RCTImageLoaderCompletionBlock)completionHandler
{
    //NSURL *temURL = [SystemFileManager baseDirForStorage:STORAGE_TEMPORARY];
    //NSURL *cacheURL = [imageURL.absoluteString pathExtension];
    //NSArray *splitArr = [imageURL.absoluteString componentsSeparatedByString:@"/"];
    //NSString *fileName = [splitArr lastObject];
    //NSURL *cacheURL = [temURL URLByAppendingPathComponent:fileName];
    
    NSString *parment = [NSString stringWithFormat:@"%@,w_%.2f,h_%.2f",imageURL.absoluteString,size.width,size.height];
    NSDictionary *params = @{@"parment": parment };
    
    NSString *cacheKey = parment;
    
    NSString *urlString = defaultDownUrl;
    if ([imageURL.absoluteString hasPrefix:@"https://"] || [imageURL.absoluteString hasPrefix:@"http://"]) {
        urlString = imageURL.absoluteString;
        cacheKey = urlString;
        params = nil;
    }
    
    UIImage *cacheImage = [YuanXinImageCache loadImageFromSDImageCacheForKey:cacheKey];
    if (cacheImage) {
        completionHandler(nil, cacheImage);
        return nil;
    }
    
    __block NSURLSessionDataTask *dataTask = nil;
    dataTask = [[NetworkingManager shareInstance]
                YuanXinDownloadImageFile:urlString
                parameters:params
                downloadProgress:nil
                success:^(NSURLSessionDataTask *task, id responseObject) {
                    completionHandler(nil, responseObject);
                    [YuanXinImageCache storeImage:responseObject bySDImageCacheForKey:cacheKey];
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error){
                    completionHandler(error, nil);
                }];
    return ^{
        [dataTask cancel];
    };
}

@end
